<?php

namespace Qwadmin\Controller;
class ContentController extends \Think\Controller{
    /**
     *  推广展示内容
     */
    public function index(){
        $id = I("id" , 0 , 'intval');
        $domain = D("domain")->getDomain(1);
        $chapter = M("referral_links")->field("id,uid,chapterid,bookid")->where(['id' => $id])->find();
        $content = redis(1)->get("content_{$chapter['chapterid']}");
        $chapter_name = redis(1)->get("chapter_name_{$chapter['chapterid']}");
        
        //如果redis记录不存在，则取记录
        if(!$content || ! $chapter_name){
            $chapter_row = M("bookchapter")->field("chapter_name,route")
                            ->where(['id' => $chapter['chapterid']])
                            ->find();
            $content = file_get_contents(NOVEL_ROOT . $chapter_row['route']);
            $chapter_name = $chapter_row['chapter_name'] ;
            redis(1)->set("content_{$chapter['chapterid']}" , $content);
            redis(1)->set("chapter_name_{$chapter['chapterid']}" , $chapter_name );
        }
        
        //获取下一章
        $sql = "select id from go_bookchapter "
                . "where sort > (select sort from go_bookchapter "
                . "where id= {$chapter['chapterid']}  ) "
                . "and tid ={$chapter['bookid']} "
                . "order by sort  asc LIMIT 1";
       
        //获取上一章
        $prev_sql = "select id from go_bookchapter "
                . "where sort < (select sort from go_bookchapter "
                . "where id= {$chapter['chapterid']}  ) "
                . "and tid ={$chapter['bookid']} "
                . "order by sort  desc LIMIT 1";
               
        $model = M();
        $next_id = $model->query($sql);
        $prev_id = $model->query($prev_sql);
        
        $this->assign("domain" , $domain);
        $this->assign("chapter" , $chapter);
        $this->assign("nextid" , $next_id[0]['id']);
        $this->assign("previd" , $prev_id[0]['id']);
        $this->assign("data" , [
            'chapter_name'  => $chapter_name ,
            'content'       => $content
        ]);
        $this->display();
    }
    
    /**
     *  增加阅读数
     */
    public function incrview(){
        $id = I("id" , 0 , 'intval');
        M("referral_links")->where(['id' => $id])->setInc("hits" , 1);
    }
}
